package lambda;

import org.junit.Test;

import java.util.Objects;
import java.util.Optional;

/**
 * @author long
 */
public class LambdaOptional {

    @Test
    public void test1(){
        People people = new People();

        // ofNullable 参数可以为null
        Optional.ofNullable(people).ifPresent(System.out::println);

        // of 参数不可以为null,为null会抛空指针
        Optional.of(people).ifPresent(System.out::println);

        // map 映射 People -> name(String)  orElse value的值为null，则返回默认值
        String name = Optional.of(people).map(People::getName).orElse("defaultName");

        // orElseGet 懒加载 如果value的值不为空，直接返回value，为null再计算默认值
        name = Optional.of(people).map(People::getName).orElseGet(()->{return 1+"";});

        // orElseThrow 不为null则返回数据，如果为null则抛异常
        people.setName("hello");
        name = Optional.of(people).map(People::getName).orElseThrow(()-> new RuntimeException("异常信息"));

        // filter 判断value是否匹配断言，匹配则返回当前Optional，否则返回空Optional
        name = Optional.of(people).map(People::getName).filter(n-> Objects.equals("tom",n)).orElse(null);

        // isPresent 判断是否不为null  get获取value值
        Optional<People> optional = Optional.of(people);
        if(optional.isPresent()){
            System.out.println(optional.get());
        }

        // ifPresent(Consumer<? super T> consumer) 如果value值存在，则消费这个value
        optional.ifPresent(System.out::println);

        // flatMap 平铺 解决Optional嵌套问题 返回 Optional<People>
        Optional<People> user = Optional.of("hello").flatMap(name2 -> {
            People p = new People();
            return Optional.of(p);
        });

    }

}
